package com.example.cangzhou.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.cangzhou.entity.User;
import com.example.cangzhou.mapper.UserMapper;
import com.example.cangzhou.result.Result;
import com.example.cangzhou.service.UserService;
import com.example.cangzhou.utils.JwtUtil;
import com.example.cangzhou.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public Result<UserVo> login(String account, String password) {
        User one = new LambdaQueryChainWrapper<>(baseMapper)
                .eq(User::getAccount, account)
                .eq(User::getPassword, password)
                .one();
        if (one == null) {
            return Result.error("用户名或密码错误");
        }
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(one, userVo);

        userVo.setToken(JwtUtil.createJWT(
                1000 * 60 * 60 * 24 * 7,
                BeanUtil.beanToMap(one)));
        return Result.success(userVo);
    }

    @Override
    public Result<UserVo> register(UserVo userVo) {
        User one = new LambdaQueryChainWrapper<>(baseMapper)
                .eq(User::getAccount, userVo.getAccount())
                .one();
        if (one != null) {
            return Result.error("账号已存在");
        }
        User user = new User();
        user.setAccount(userVo.getAccount());
        user.setUsername(userVo.getUsername());
        user.setPassword(userVo.getPassword());
        user.setEmail(userVo.getEmail());
        user.setPhone(userVo.getPhone());
        user.setGender(userVo.getGender());
        user.setStatus(1);
        user.setType(userVo.getType() == null ? 2 : userVo.getType());
        baseMapper.insert(user);

        return Result.success();
    }


    @Override
    public Page<User> pageList(Page<User> page, User user) {
        return new LambdaQueryChainWrapper<>(baseMapper)
                .like(StringUtils.isNotBlank(user.getUsername()), User::getUsername, user.getUsername())
                .like(StringUtils.isNotBlank(user.getEmail()), User::getEmail, user.getEmail())
                .like(StringUtils.isNotBlank(user.getPhone()), User::getPhone, user.getPhone())
                .like(user.getStatus() != null, User::getStatus, user.getStatus())
                .page(page);  // MP 会自动处理分页
    }
}
